// pages/health/history.js
Page({
  data: {
    currentFilter: 'all',
    allRecords: [],
    filteredRecords: [],
    filteredStats: {
      totalRecords: 0,
      averageMood: 0,
      positiveDays: 0
    }
  },

  onLoad: function () {
    this.loadMoodRecords();
  },

  onShow: function () {
    this.loadMoodRecords();
  },

  // 加载心情记录
  loadMoodRecords: function () {
    const records = wx.getStorageSync('moodRecords') || [];
    this.processRecords(records);
  },

  // 处理记录数据
  processRecords: function (records) {
    const processedRecords = records.map(record => {
      const date = new Date(record.timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return {
        ...record,
        timeStr: `${hours}:${minutes}`
      };
    });

    processedRecords.sort((a, b) => b.timestamp - a.timestamp);

    this.setData({
      allRecords: processedRecords
    });

    this.applyFilter();
  },

  // 设置筛选条件
  setFilter: function (e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      currentFilter: filter
    });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter: function () {
    const { currentFilter, allRecords } = this.data;
    let filteredRecords = [];

    if (currentFilter === 'all') {
      filteredRecords = allRecords;
    } else if (currentFilter === 'week') {
      const now = new Date();
      const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      filteredRecords = allRecords.filter(record => {
        const recordDate = new Date(record.timestamp);
        return recordDate >= weekStart;
      });
    } else if (currentFilter === 'month') {
      const now = new Date();
      const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
      filteredRecords = allRecords.filter(record => {
        const recordDate = new Date(record.timestamp);
        return recordDate >= monthStart;
      });
    }

    this.setData({
      filteredRecords: filteredRecords
    });

    this.calculateStats(filteredRecords);
  },

  // 计算统计信息
  calculateStats: function (records) {
    if (records.length === 0) {
      this.setData({
        filteredStats: {
          totalRecords: 0,
          averageMood: 0,
          positiveDays: 0
        }
      });
      return;
    }

    const totalMood = records.reduce((sum, record) => sum + record.level, 0);
    const averageMood = (totalMood / records.length).toFixed(1);
    const positiveDays = records.filter(record => record.level >= 4).length;

    this.setData({
      filteredStats: {
        totalRecords: records.length,
        averageMood: parseFloat(averageMood),
        positiveDays: positiveDays
      }
    });
  },

  // 编辑记录
  editRecord: function (e) {
    wx.showModal({
      title: '编辑记录',
      content: '编辑功能开发中，敬请期待！',
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 删除记录
  deleteRecord: function (e) {
    const record = e.currentTarget.dataset.record;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除 ${record.date} 的心情记录吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deleteMoodRecord(record);
        }
      }
    });
  },

  // 删除心情记录
  deleteMoodRecord: function (record) {
    let records = wx.getStorageSync('moodRecords') || [];
    records = records.filter(item => item.timestamp !== record.timestamp);
    wx.setStorageSync('moodRecords', records);
    
    this.loadMoodRecords();
    
    wx.showToast({
      title: '删除成功',
      icon: 'success',
      duration: 2000
    });
  }
});
